package org.cliff.message.platform.management.domain;

import java.io.Serializable;
import java.util.Optional;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;

/**
 * 消息平台Rest响应
 *
 * @author 刘文
 * @date 2023/10/30
 */
@Data
@Accessors(chain = true)
@ApiModel("消息平台Rest响应")
public class MPR<T> implements Serializable {

    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = 1L;

    /**
     * 业务错误码
     */
    @ApiModelProperty("业务错误码")
    private long code;
    /**
     * 结果集
     */
    @ApiModelProperty("结果集")
    private T data;
    /**
     * 描述
     */
    @ApiModelProperty("描述")
    private String msg;

    public MPR() {
        // to do nothing
    }

    public MPR(IErrorCode errorCode) {
        errorCode = Optional.ofNullable(errorCode).orElse(ApiErrorCode.FAILED);
        this.code = errorCode.getCode();
        this.msg = errorCode.getMsg();
    }

    public static <T> MPR<T> ok(T data) {
        ApiErrorCode aec = ApiErrorCode.SUCCESS;
        if (data instanceof Boolean && Boolean.FALSE.equals(data)) {
            aec = ApiErrorCode.FAILED;
        }
        return restResult(data, aec);
    }

    public static <T> MPR<T> failed(String msg) {
        return restResult(null, ApiErrorCode.FAILED.getCode(), msg);
    }

    public static <T> MPR<T> failed(long code, String msg) {
        return restResult(null, code, msg);
    }

    public static <T> MPR<T> failed(IErrorCode errorCode) {
        return restResult(null, errorCode);
    }

    public static <T> MPR<T> restResult(T data, IErrorCode errorCode) {
        return restResult(data, errorCode.getCode(), errorCode.getMsg());
    }

    public static <T> MPR<T> restResult(T data, long code, String msg) {
        MPR<T> apiResult = new MPR<>();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMsg(msg);
        return apiResult;
    }
}
